var COMM = COMM || {};
/**
 * desc: 创建命名空间
 * usage： COMM.namespace（"com.mjh.best"） 或 COMM.ns("com.mjh.best")
 * @param space
 */
COMM.namespace = function(space){
	var c = window;
	var objects = space.split(".");
	for(var i=0;i<objects.length;i++){
		c[objects[i]] =  c[objects[i]] || {};
		c = c[objects[i]];
	}
};
COMM.ns = COMM.namespace;

/**
 * desc: 封转了js组件的加载方式，同时加载多个js或css文件
 * usage: COMM.lib.load("dialog");
 */
COMM.lib = (function(){
	
	var loadlib, lib, script, css;
	var head = document.getElementsByTagName("head")[0] || document.documentElement;
	//定义组件
	var libs = {
		form : {type:"js", url:"/script/lib/jquery/jquery.form.js"},
		bgiframe : {type:"js",url:"bgifffffffffffffffff"},
		tooltip : [
		  {type:"js",url:""},
		  {type:"css",url:""}
		],
		pager : [
 		  {type:"js",url:"/script/lib/jquery.pagination/jquery.pagination.js"},
 		  {type:"css",url:"/script/lib/jquery.pagination/pagination.css"}
 		],
		dialog : [
		   {type:"js",url:"/script/lib/artDialog3.0.4/artDialog.js", callback:function(){} }
		],
		editor : [
		   {type:"js",url:"/script/lib/kindeditor3.5.2/kindeditor.js"}
		]
	};
	var load = function(name){
		loadlib = libs[name];
		if(loadlib){
			if($.isArray(loadlib)){
				for(var i=0;i<loadlib.length;i++){
					lib = loadlib[i];
					if(typeof lib === "string"){
						load(lib);
					} else {
						write(lib);
					}
				}
			} else {
				write(loadlib);
			}
		}
	};
	var write = function(obj){
		if(obj.type == "js"){
			script = document.createElement("script");
			script.type = "text/javascript";
			script.src = obj.url;
			head.appendChild(script);
			//如果定义了回调函数，则在加载完js后执行回调函数
			if(typeof obj.callback === "function"){
				script.onload = script.onreadystatechange = function() {
					if (!script.readyState || 'loaded' === script.readyState ||'complete' === script.readyState) {
						script.onload = script.onreadystatechange = null;
						obj.callback();
					};
				};
			}
		} else {
			css = document.createElement("link");
			css.rel = "stylesheet";
			css.type = "text/css";
			css.href = obj.url;
			head.appendChild(css);
		}
	} ;
	return {
		load : function(libName){
			load(libName);
		}
	};
})();

/**
 * 日期格式化函数 
 * alert(new Date().format("yyyy-MM-dd"));
 * alert(new Date("january 12 2008 11:12:30").format("yyyy-MM-dd hh:mm:ss"));
 * 
 * @param format
 * @return
 */
Date.prototype.format = function(format) // author: meizz
{
	var o = {
		"M+" : this.getMonth() + 1, // month
		"d+" : this.getDate(), // day
		"h+" : this.getHours(), // hour
		"m+" : this.getMinutes(), // minute
		"s+" : this.getSeconds(), // second
		"q+" : Math.floor((this.getMonth() + 3) / 3), // quarter
		"S" : this.getMilliseconds()  // millisecond
	};
	if (/(y+)/.test(format)){
		format = format.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}
	for ( var k in o){
		if (new RegExp("(" + k + ")").test(format)){
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
					: ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
};
/**
 * 将String类型解析为Date类型
 *  parseDate(‘2006-1-1′) return new Date(2006,0,1)
 *  parseDate(‘ 2006-1-1 ‘) return new Date(2006,0,1)
 *  parseDate(‘2006-1-1 15:14:16′) return new Date(2006,0,1,15,14,16)
 *  
 */
COMM.parseDate = function(str) {
	if (typeof str == "string") {
		var results = str.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) *$/);
		if (results && results.length > 3)
			return new Date(parseInt(results[1]), parseInt(results[2]) - 1,
					parseInt(results[3]));
		results = str
				.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2}) *$/);
		if (results && results.length > 6)
			return new Date(parseInt(results[1]), parseInt(results[2]) - 1,
					parseInt(results[3]), parseInt(results[4]),
					parseInt(results[5]), parseInt(results[6]));
		results = str
				.match(/^ *(\d{4})-(\d{1,2})-(\d{1,2}) +(\d{1,2}):(\d{1,2}):(\d{1,2})\.(\d{1,9}) *$/);
		if (results && results.length > 7)
			return new Date(parseInt(results[1]), parseInt(results[2]) - 1,
					parseInt(results[3]), parseInt(results[4]),
					parseInt(results[5]), parseInt(results[6]),
					parseInt(results[7]));
	}
	return null;
};
//打印日志
var log = function(obj){
	try{
		console.log(obj);
	} catch(e) {
		alert(obj);
	}
};

 //扩展jquery的ajax方法
(function($){
	var defaultPostConfig = {
		type: "POST",
		dataType  : "json",
		error : function(){
			alert("操作失败！");
		}
	};
	$.postJson = jQuery.postJson =  function(config){
		config = jQuery.extend({}, defaultPostConfig, config);
		$.ajax(config);
	};
	//封装jquery.form
	var defaultFormConfig = {
		type : 'post' ,       // 'get' or 'post', override for form's 'method' attribute 
		dataType : 'json',        // 'xml', 'script', or 'json' (expected server response type) 
		error : function(){
			alert("操作失败！");
		}
	};
	$.postForm = function(config){
		config = jQuery.extend({}, defaultFormConfig, config);
		$(config.formId).ajaxSubmit(config);
	} ;
	//同步ajax获取数据
	var defaultAsyncConfig = {
		type: "GET",
		async : false,
		dataType  : "html",
		error : function(){
			alert("操作失败！");
		}
	};
	$.asyncGet = function(config){
		config = jQuery.extend({}, defaultAsyncConfig, config);
		$.ajax(config);
	};
})(jQuery);

//选中下拉框
(function($){
	$.fn.select = function(val){
		$(this).find("option").each(function(){
			if($(this).val() == val){
				$(this).attr("selected", true);
				return;
			}
		});
	};
})(jQuery);


